using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Infrastructure.Data;
using OrderingSystem.API.Models;
using System.Collections.Generic;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("caipinfenlei")]
    public class CategoryController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public CategoryController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有分类列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<R>> GetCategories()
        {
            var categories = await _context.Categories
                .Select(c => new
                {
                    id = c.id,
                    addtime = c.addtime,
                    caipinfenlei = c.caipinfenlei
                })
                .ToListAsync();

            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = categories
            });
        }

        /// <summary>
        /// 获取分页分类列表
        /// </summary>
        [HttpGet("page")]
        public async Task<ActionResult<R>> GetCategoryPage([FromQuery] int page, [FromQuery] int limit, [FromQuery] string sort, 
            [FromQuery] string caipinfenlei = null)
        {
            try
            {
                // 构建查询
                var query = _context.Categories.AsQueryable();

                // 应用筛选条件
                if (!string.IsNullOrEmpty(caipinfenlei))
                {
                    // 移除百分号以支持LIKE查询
                    caipinfenlei = caipinfenlei.Replace("%", "");
                    query = query.Where(c => EF.Functions.Like(c.caipinfenlei, $"%{caipinfenlei}%"));
                }

                // 计算总记录数
                var total = await query.CountAsync();

                // 应用排序和分页
                var sortField = string.IsNullOrEmpty(sort) ? "id" : sort;
                var sortProperty = typeof(Category).GetProperty(sortField);
                
                if (sortProperty != null)
                {
                    // 默认按ID升序排序
                    query = query.OrderBy(c => c.id);
                }

                var categories = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToListAsync();

                // 返回分页结果
                return Ok(new R
                {
                    code = 0,
                    msg = "获取成功",
                    data = new
                    {
                        total,
                        list = categories,
                        page,
                        limit
                    }
                });
            }
            catch (Exception ex)
            {
                return Ok(new R { code = 1, msg = $"获取分类列表失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取单个分类详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<R>> GetCategory(long id)
        {
            var category = await _context.Categories
                .Select(c => new
                {
                    id = c.id,
                    addtime = c.addtime,
                    caipinfenlei = c.caipinfenlei
                })
                .FirstOrDefaultAsync(c => c.id == id);

            if (category == null)
            {
                return Ok(new R { code = 1, msg = "未找到该分类" });
            }

            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = category
            });
        }

        /// <summary>
        /// 添加分类
        /// </summary>
        [Authorize(Roles = "Admin")]
        [HttpPost("save")]
        public async Task<ActionResult<R>> CreateCategory([FromBody] Category model)
        {
            var category = new Category
            {
                caipinfenlei = model.caipinfenlei,
                addtime = DateTime.Now
            };

            _context.Categories.Add(category);
            await _context.SaveChangesAsync();

            return Ok(new R
            {
                code = 0,
                msg = "添加成功",
                data = new
                {
                    id = category.id,
                    addtime = category.addtime,
                    caipinfenlei = category.caipinfenlei
                }
            });
        }

        /// <summary>
        /// 更新分类
        /// </summary>
        [Authorize(Roles = "Admin")]
        [HttpPost("update")]
        public async Task<ActionResult<R>> UpdateCategory([FromBody] Category model)
        {
            var category = await _context.Categories.FindAsync(model.id);
            if (category == null)
            {
                return Ok(new R { code = 1, msg = "未找到该分类" });
            }

            category.caipinfenlei = model.caipinfenlei;

            await _context.SaveChangesAsync();

            return Ok(new R
            {
                code = 0,
                msg = "更新成功",
                data = new
                {
                    id = category.id,
                    addtime = category.addtime,
                    caipinfenlei = category.caipinfenlei
                }
            });
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        [Authorize(Roles = "Admin")]
        [HttpPost("delete")]
        public async Task<ActionResult<R>> DeleteCategory([FromBody] IdModel model)
        {
            var category = await _context.Categories
                .FirstOrDefaultAsync(c => c.id == model.id);

            if (category == null)
            {
                return Ok(new R { code = 1, msg = "未找到该分类" });
            }

            // 检查是否有菜品使用此分类
            var hasDishes = await _context.Dishes
                .AnyAsync(d => d.caipinfenlei == category.caipinfenlei);

            if (hasDishes)
            {
                return Ok(new R { code = 1, msg = "该分类下存在菜品，无法删除" });
            }

            _context.Categories.Remove(category);
            await _context.SaveChangesAsync();

            return Ok(new R { code = 0, msg = "删除成功" });
        }
    }

    /// <summary>
    /// 通用响应格式
    /// </summary>
    public class R
    {
        public int code { get; set; }
        public string msg { get; set; }
        public object data { get; set; }
    }

    /// <summary>
    /// ID请求模型
    /// </summary>
    public class IdModel
    {
        public long id { get; set; }
    }
} 